<template>
  <div class="home">
    <h1>微博首页</h1>
<!--javascript:void(0)废掉超链接的跳转功能-->
    <div v-if="user==null">
      <a href="javascript:void(0)" @click="reg()">注册</a>
      <a href="javascript:void(0)" @click="login()">登录</a>
    </div>
    <div v-else>
      <h2>欢迎{{user.nickname}}回来!</h2>
      <a href="javascript:void(0)" @click="post()">发微博</a>
      <a href="javascript:void(0)" @click="logout()">退出登录</a>
    </div>
    <hr>
<!-- 遍历显示微博列表 -->
    <div v-for="weibo in arr">

      <h3>
        <a href="javascript:void(0)" @click="detail(weibo.id)">
          {{weibo.nickname}}:{{weibo.content}}
        </a>
      </h3>
    </div>
  </div>
</template>

<script>
export default {
  name: 'HomeView',
  data() {
    return {
      user: {},arr:[]
    }
  },
  methods: {
    detail(id){
      //跳转页面并且传递id
      this.$router.push('/detail?id='+id);
    },
    post(){
      this.$router.push('/post');
    },
    logout(){
      if(confirm("您确认退出登录吗?")){
        localStorage.clear();
        this.user=null;
      }
    },
    reg() {
      this.$router.push('/reg');
    },
    login(){
      this.$router.push('/login');
    }
  },
  mounted() {
    //进入页面就需要执行的代码写在此处
    //此方法是Vue对象的生命周期方法, 生命周期指从创建到销毁,
    // 生命周期方法会由Vue对象自动调用
    //判断localStorage.user是否有值,有值将Json格式字符串转成user对象没值则为null
    this.user = localStorage.user?JSON.parse(localStorage.user):null;

    //请求微博列表
    this.axios.get("http://localhost:8080/v1/weibos/")
    .then((response)=>{
      if (response.data.code==1){
        this.arr = response.data.data;
      }
    })

  }

}
</script>
